#!/usr/bin/env python3
"""
配置向导 - 交互式配置 Worker 服务
"""

import json
import os
import sys
import socket


def get_machine_name():
    """获取默认机器名"""
    return socket.gethostname()


def input_with_default(prompt, default):
    """带默认值的输入"""
    value = input(f"{prompt} [{default}]: ").strip()
    return value if value else default


def yes_no_prompt(prompt, default=True):
    """是/否提示"""
    default_str = "Y/n" if default else "y/N"
    value = input(f"{prompt} [{default_str}]: ").strip().lower()
    if not value:
        return default
    return value in ('y', 'yes', '是')


def ensure_config_structure(config):
    """确保配置文件具有所有必需的键"""
    # 初始化所有必需的顶级键
    if 'worker' not in config:
        config['worker'] = {}
    if 'api' not in config:
        config['api'] = {}
    if 'transcription' not in config:
        config['transcription'] = {}
    if 'polish' not in config:
        config['polish'] = {}

    # 配置格式迁移：backend.api_url -> api.base_url
    if 'backend' in config and 'api_url' in config['backend']:
        print("⚠️  检测到旧版配置格式，正在自动迁移...")
        config['api']['base_url'] = config['backend']['api_url']
        print(f"   已迁移: backend.api_url -> api.base_url")

    return config


def main():
    print("=" * 50)
    print("  视频转录 Worker 配置向导")
    print("=" * 50)
    print()

    # 读取现有配置
    config_path = "config/worker_config.json"
    if os.path.exists(config_path):
        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        print("✓ 找到现有配置，将基于现有配置进行修改")
    else:
        # 从示例加载
        example_path = "config/worker_config.example.json"
        if os.path.exists(example_path):
            with open(example_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            print("✓ 从示例配置开始")
        else:
            print("❌ 错误: 未找到配置文件")
            sys.exit(1)

    # 确保配置结构完整
    config = ensure_config_structure(config)

    print()
    print("-" * 50)
    print("  1. 基本配置")
    print("-" * 50)

    # 机器名
    current_machine = config['worker'].get('machine_name', get_machine_name())
    machine_name = input_with_default(
        "请输入机器名称（用于标识不同的 Worker）",
        current_machine
    )
    config['worker']['machine_name'] = machine_name

    # API 地址
    print()
    current_api = config['api'].get('base_url', 'http://localhost:8001')
    api_url = input_with_default(
        "请输入后台 API 地址",
        current_api
    )
    config['api']['base_url'] = api_url.rstrip('/')

    # 路径映射
    print()
    print("-" * 50)
    print("  2. 路径映射（可选）")
    print("-" * 50)
    print("如果 Excel 中的路径与本机不同（如跨平台），需要配置路径映射")
    print("例如: Excel中是 W:\\数据爬取\\ 但本机是 /Volumes/Samsung_T5/数据爬取/")
    print()

    setup_mapping = yes_no_prompt("是否配置路径映射？", False)

    if setup_mapping:
        print()
        excel_path = input("Excel 中的路径前缀（如 W:\\数据爬取\\）: ").strip()
        local_path = input("本机实际路径前缀（如 /Volumes/Samsung_T5/数据爬取/）: ").strip()

        if excel_path and local_path:
            if 'path_mapping' not in config['worker']:
                config['worker']['path_mapping'] = {}
            config['worker']['path_mapping'][excel_path] = local_path
            print(f"✓ 路径映射已配置: {excel_path} → {local_path}")

    # GPU 配置
    print()
    print("-" * 50)
    print("  3. 转录配置")
    print("-" * 50)

    # 模型选择
    print()
    print("Whisper 模型大小（影响速度和准确度）:")
    print("  - tiny: 最快，准确度一般（推荐用于测试）")
    print("  - base: 平衡（推荐用于生产）")
    print("  - small: 较慢，准确度高")
    print("  - medium/large: 非常慢，准确度最高")

    current_model = config['transcription'].get('model', 'tiny')
    model_size = input_with_default("请选择模型", current_model)
    config['transcription']['model'] = model_size

    # GPU 支持
    print()
    print("GPU 加速:")
    print("  - auto: 自动检测（推荐）")
    print("  - cuda: NVIDIA GPU")
    print("  - mps: Apple Silicon GPU")
    print("  - cpu: 仅使用 CPU")

    current_device = config['transcription'].get('device', 'auto')
    device = input_with_default("请选择设备", current_device)
    config['transcription']['device'] = device

    # 润色配置
    print()
    print("-" * 50)
    print("  4. AI 润色配置")
    print("-" * 50)

    enable_polish = yes_no_prompt(
        "是否启用 AI 润色？",
        config['polish'].get('enabled', True)
    )
    config['polish']['enabled'] = enable_polish

    if enable_polish:
        print()
        print("⚠️  AI 润色需要 DeepSeek API Key")
        print("   请手动编辑 .env 文件，添加:")
        print("   DEEPSEEK_API_KEY=your_api_key_here")

        # 自定义提示词
        print()
        use_custom_prompt = yes_no_prompt("是否使用自定义润色提示词？", False)
        if use_custom_prompt:
            print("请编辑 config/worker_config.json 中的 polish.prompt_template 字段")
        else:
            config['polish']['prompt_template'] = ""

    # 保存配置
    print()
    print("-" * 50)
    print("  配置预览")
    print("-" * 50)
    print()
    print(json.dumps(config, indent=2, ensure_ascii=False))
    print()

    if yes_no_prompt("确认保存配置？", True):
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)

        print()
        print("=" * 50)
        print("  配置保存成功！")
        print("=" * 50)
        print()
        print("配置文件位置:", config_path)
        print()
        print("下一步:")
        print("  1. 如需 AI 润色，请编辑 .env 添加 API Key")
        print("  2. 运行 Worker:")
        print("     ./start_worker.sh --excel /path/to/excel.xlsx  (macOS/Linux)")
        print("     start_worker.bat --excel C:\\path\\to\\excel.xlsx  (Windows)")
        print()
    else:
        print("❌ 配置未保存")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n❌ 已取消")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ 错误: {e}")
        sys.exit(1)
